package org.zheng.shop.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.zheng.shop.dto.MessageResponse;
import org.zheng.shop.service.FileStorageService;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/uploads")
public class FileController {
    
    @Value("${file.upload-dir}")
    private String uploadDir;
    
    @Autowired
    private FileStorageService fileStorageService;
    
    @GetMapping("/images/{fileName:.+}")
    public ResponseEntity<Resource> getImage(@PathVariable String fileName) {
        try {
            Path uploadPath = Paths.get(uploadDir);
            
            // 确保目录存在
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            Path filePath = uploadPath.toAbsolutePath().normalize().resolve(fileName);
            Resource resource = new UrlResource(filePath.toUri());
            
            if (resource.exists()) {
                return ResponseEntity.ok()
                        .contentType(MediaType.IMAGE_JPEG)
                        .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + resource.getFilename() + "\"")
                        .body(resource);
            } else {
                // 如果找不到文件，尝试在子目录中查找
                Path imagesSubdir = uploadPath.resolve("images");
                if (Files.exists(imagesSubdir)) {
                    Path imageSubdirPath = imagesSubdir.resolve(fileName);
                    if (Files.exists(imageSubdirPath)) {
                        Resource subResource = new UrlResource(imageSubdirPath.toUri());
                        return ResponseEntity.ok()
                                .contentType(MediaType.IMAGE_JPEG)
                                .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + subResource.getFilename() + "\"")
                                .body(subResource);
                    }
                }
                
                System.out.println("未找到图片文件: " + filePath);
                return ResponseEntity.notFound().build();
            }
        } catch (MalformedURLException e) {
            System.err.println("图片URL错误: " + e.getMessage());
            return ResponseEntity.notFound().build();
        } catch (IOException e) {
            System.err.println("读取图片错误: " + e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }
    
    @PostMapping("/upload")
    public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            String fileName = fileStorageService.storeFile(file);
            return ResponseEntity.ok(new MessageResponse(fileName));
        } catch (Exception e) {
            System.err.println("文件上传失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.badRequest().body(new MessageResponse("文件上传失败: " + e.getMessage()));
        }
    }
} 